package org.zjx.analysis.analyze.tap;

import lombok.Getter;
import org.zjx.analysis.analyze.window.AbstractWindowAnalyzer;
import org.zjx.analysis.identify.IdentifyFontUtil;
import org.zjx.analysis.identify.IdentifyTessUtil;
import org.zjx.analysis.util.PaneUtil;
import org.zjx.command.enums.FontType;
import org.zjx.command.util.ImageUtil;
import org.zjx.window.window.IWindow;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Getter
public abstract class BaseTabAnalysis extends AbstractWindowAnalyzer {
    protected Point location;

    public BaseTabAnalysis(String analyzerName,IWindow window) {
        super(analyzerName, "小地图", window);
    }

    @Override
    public void analyze(BufferedImage image) {
        this.location = location();
    }

    private Point location() {
        Rectangle locationRect = conversion(windowArea,new Rectangle(getContentArea().x - 50, getContentArea().y -30,getContentArea().width + 100,getContentArea().height + 30));
        PaneUtil paneUtil = new PaneUtil(ImageUtil.cutImage(screenshot,locationRect), 5, Collections.singletonList(new Color(248, 252, 248)));
        List<Rectangle> rects = paneUtil.detectRect();
        if (rects.isEmpty()) return null;

        Rectangle rect = new Rectangle(rects.get(0).x + 1, rects.get(0).y + 1, rects.get(0).width - 2, rects.get(0).height - 2);
        BufferedImage bufferedImage = ImageUtil.cutImage(screenshot, conversion(locationRect,rect));
//        String locationStr = IdentifyTessUtil.tessIdentify(bufferedImage);
        String locationStr = IdentifyFontUtil.identifyAsString(bufferedImage, Collections.singletonList(Color.YELLOW), FontType.LOCATION,0,false);
        return matcherMap(locationStr);
    }


    public abstract Rectangle getContentArea();


    private Point matcherMap(String location) {
        location = location.replace(",","，");
        String regex = "([0-9]+)，([0-9]+)";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(location);
        if (matcher.find()) {
            int x = Integer.parseInt(matcher.group(1));
            int y = Integer.parseInt(matcher.group(2));
            return new Point(x, y);
        } else {
            return null;
        }
    }
}
